package com.controller;

import com.Dto.LoginDto;
import com.Dto.OldDataDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.MesIpcService;
import com.util.*;
import org.apache.commons.lang3.StringUtils;
//import org.jsoup.Connection;
//import org.jsoup.Connection.Response;
//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.stream.Collectors;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

@CrossOrigin
@RestController
@RequestMapping("/server")
public class ServerController {

    @Autowired
    private MesIpcService mesIpcService;

    /*
     *   _老化后对接通用接口
     */
    @RequestMapping(value = "/getSocketData", method = RequestMethod.POST, produces = "application/json")
    public Result<String> getSocketData(@RequestBody String mesJsonString) {
        MesJson mesJson = JSON.parseObject(mesJsonString, MesJson.class);
        System.out.println("IMS发送的数据:data=" + mesJson.getData() + ";extend=" + mesJson.getExtend() + ";devVersion=" + mesJson.getDevVersion());
        Result<String> result = startServer(mesJson);
        System.out.println("处理完后返回数据:code=" + result.getCode() + ";message=" + result.getMsg() + ";data=" + result.getData() + ";extend=" + result.getExtend());
        return result;
    }


    public Result<String> startServer(MesJson mesJson) {
        Result<String> result = new Result<>();
        //阻塞等待IMS系统请求
        Integer type = 1;  //产品类型,1为车载，2为出租车；这里先初始化为1
        String code = mesJson.getCode();
        String carType = mesJson.getCarType();//mes返回的产品类型
        if (StringUtils.isNotBlank(carType)) {
            type = Integer.parseInt(carType);
        }
        if (StringUtils.isNotBlank(code)) {
            if (code.equals("send")) {
                String dataString = mesJson.getData(); //命令代码
                String inputData = mesJson.getInputData(); //MES输入数据
                String extend = mesJson.getExtend(); //
                String devVersion = mesJson.getDevVersion(); //设备版本
                JSONObject map = JSON.parseObject(extend);
                if (map == null) {
                    map = new JSONObject();
                }
                try {
//						FrameDto frameDto = null;
                    JSONObject json = new JSONObject();
//						if(dataString.equals("order_04")) {     //mac地址写入，需要前端输入
//							if(StringUtils.isNotBlank(inputData)) {
//								if(inputData.length()<12) {
//											result.setCode(500);
//											result.setMsg("扫描输入数据："+inputData+"长度不正确");
//											return result;
//									}
//									byte[] toBytes = FrameUtil.hexStringToBytes(inputData);
//									frameDto= FrameUtil.creatDto_04(toBytes);
//									json.put("macAddress", inputData);
//							}else {
//									result.setCode(501);
//									result.setMsg("请扫描MAC地址");
//									return result;
//							}
//						}if(dataString.equals("order_03")) {    //mac地址获取，需要前端输入并对比
//							if(StringUtils.isNotBlank(inputData)) {
//								if(inputData.length()<12) {
//											result.setCode(500);
//											result.setMsg("扫描输入数据："+inputData+"长度不正确");
//											return result;
//									}
//									map.put("value", inputData);
//									frameDto= FrameUtil.createData(dataString);
//									json.put("macAddress", inputData);
//								}else {
//									result.setCode(501);
//									result.setMsg("请扫描MAC地址");
//									return result;
//								}
//						}else if("order_25".equals(dataString)) {     //产品SN写入，需要前端输入
//								if(StringUtils.isNotBlank(inputData)) {
//									frameDto=FrameUtil.creatDto_25(inputData);
//									json.put("sn", inputData);
//								}else {
//									result.setCode(501);
//									result.setMsg("请扫描产品SN");
//									return result;
//								}
//						}else if("order_1c".equals(dataString.toLowerCase())){  //手机号写入，需要前端输入
//								if(StringUtils.isNotBlank(inputData)) {
//									frameDto=FrameUtil.creatDto_1C(inputData);
//									json.put("phoneNumber", inputData);
//								}else {
//									result.setCode(501);
//									result.setMsg("请扫描手机号");
//									return result;
//								}
//						}else if("order_27".equals(dataString.toLowerCase())){   //终端ID写入,需要前端输入
//								if(StringUtils.isNotBlank(inputData)) {
//									frameDto=FrameUtil.creatDto_27(inputData);
//									json.put("terminalId", inputData);
//								}else {
//									result.setCode(501);
//									result.setMsg("请扫描终端ID");
//									return result;
//								}
//						}else if("order_0d".equals(dataString.toLowerCase())){  //机型配置,需要前端输入机型
//								String machineTypeSet = map.getString("machineTypeSet");
//								if(StringUtils.isNotBlank(machineTypeSet)) {
//										frameDto=FrameUtil.creatDto_0D(machineTypeSet);
//										json.put("machineTypeSet", machineTypeSet);
//								}else {
//										result.setCode(500);
//										result.setMsg("工单未配置机型配置");
//										return result;
//								}
//						}else if("order_producerid_old".equals(dataString.toLowerCase())){ //制造商ID写入（注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>5) {
//									result.setCode(500);
//									result.setMsg("输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.PRODUCER_ID_WRITE_OLD);
//								json.put("produceridOld", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描制造商ID");
//								return result;
//							}
//						}else if("order_terminalno_old".equals(dataString.toLowerCase())){ //终端型号写入（注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>20) {
//									result.setCode(500);
//									result.setMsg("扫描输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.TERMINAL_NO_WRITE_OLD);
//								json.put("terminalnoOld", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描终端型号");
//								return result;
//							}
//						}else if("order_producerid_new".equals(dataString.toLowerCase())){ // 制造商ID写入（新注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>11) {
//									result.setCode(500);
//									result.setMsg("扫描输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.PRODUCER_ID_WRITE_NEW);
//								json.put("produceridNew", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描制造商ID");
//								return result;
//							}
//						}else if("order_terminalid_new".equals(dataString.toLowerCase())){ // 终端ID写入（新注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>30) {
//									result.setCode(500);
//									result.setMsg("扫描输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.TERMINAL_ID_WRITE_NEW);
//								json.put("terminalidNew", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描终端ID");
//								return result;
//							}
//						}else if("order_terminalphone_new".equals(dataString.toLowerCase())){ // 终端手机号写入（新注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>20) {
//									result.setCode(500);
//									result.setMsg("扫描输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.TERMINAL_PHONE_WRITE_NEW);
//								json.put("terminalphoneNew", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描终端手机号");
//								return result;
//							}
//						}else if("order_terminalno_new".equals(dataString.toLowerCase())){ // 终端型号写入（新注册界面）
//							if(StringUtils.isNotBlank(inputData)) {
//								byte[] ascii = FrameUtil.stringToAscii(inputData);
//								if(ascii.length>20) {
//									result.setCode(500);
//									result.setMsg("扫描输入数据："+inputData+"长度不正确");
//									return result;
//								}
//								frameDto = FrameUtil.creatDto_AsciiInput(inputData,OrderTye.TERMINAL_NO_WRITE_NEW);
//								json.put("terminalnoNew", inputData);
//								map.put("value", inputData);
//							}else {
//								result.setCode(501);
//								result.setMsg("请扫描终端型号");
//								return result;
//							}
//						}else {
//							frameDto = FrameUtil.createData(dataString);  //除了上面特殊的命令外，这里全部使用通用处理方法
//						}
//
                    LoginDto loginDto = new LoginDto();
                    JSONObject loginData = JSON.parseObject(mesJson.getLoginData());
                    if (loginData.getString("ip") == null) {
                        result.setCode(500);
                        result.setMsg("工单交互方案未配置IP,用户名密码");
                        return result;
                    }
                    Map<String, String> cookiesMap = new HashMap<String, String>();
                    if ("1".equals(devVersion)) {
                        String macUrl = "http://" + loginData.getString("ip") + "/getparameter.json";
                        String versionUrl = "http://" + loginData.getString("ip") + "/device.rsp";
                        String loginUrl = "http://" + loginData.getString("ip") + "/logincheck.rsp?type=1";
                        String uploadUrl = "http://" + loginData.getString("ip") + "/upload.rsp?callbackfun=window.parent.uploadsuccess&filetype=importparam";
                        loginDto.setMacUrl(macUrl);
                        loginDto.setVersionUrl(versionUrl);
                        loginDto.setUploadUrl(uploadUrl);
                        loginDto.setLoginUrl(loginUrl);
                        cookiesMap = mesIpcService.getCookiesMap(loginDto.getLoginUrl(), loginData.getString("userName"), loginData.getString("passWord"));
                        if (cookiesMap.size() == 0) {
                            result.setCode(500);
                            result.setMsg("登录出错");
                            return result;
                        }
                    } else if ("2".equals(devVersion)) {
                        String macUrl = "http://" + loginData.getString("ip") + "/";
                        String versionUrl = "http://" + loginData.getString("ip") + "/devapi/v1/basic/";
                        String loginUrl = "http://" + loginData.getString("ip") + "/devapi/v1/basic/key";
                        String uploadUrl = versionUrl + "fileconfig2pc";
                        loginDto.setMacUrl(macUrl);
                        loginDto.setLoginUrl(loginUrl);
                        loginDto.setVersionUrl(versionUrl);
                        loginDto.setUploadUrl(uploadUrl);
                        cookiesMap = mesIpcService.getCookiesMap2(loginDto.getLoginUrl(), loginData.getString("userName"), loginData.getString("passWord"), 1, 1);
                        if (cookiesMap.size() == 0) {
                            throw new Exception("登录出错");
                        } else if (cookiesMap.get("sessionId") == null || cookiesMap.get("sessionId").equals("")) {
                            throw new Exception("登录出错");
                        }
                    } else {
                        result.setCode(500);
                        result.setMsg("对接的设备版本不能识别：" + devVersion);
                        return result;
                    }

                    OldDataDto oldDataDto = new OldDataDto(); // 设备采集数据
                    if ("order_02".equals(dataString.toLowerCase())) {  //版本信息比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_02(result, loginDto, cookiesMap, oldDataDto, map, json, type);
                        } else {  //2.0版本对接
                            dealOrder_02_2(result, loginDto, cookiesMap, oldDataDto, map, json, type);
                        }
                    } else if ("order_27".equals(dataString.toLowerCase())) {  //写入终端ID
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_27(result, loginDto, cookiesMap, inputData);
                        } else {  //2.0版本对接
                            dealOrder_27_2(result, loginDto, cookiesMap, inputData);
                        }
                    } else if ("order_1c".equals(dataString.toLowerCase())) {  //写入手机号
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_1c(result, loginDto, cookiesMap, inputData);
                        } else {  //2.0版本对接
                            dealOrder_1c_2(result, loginDto, cookiesMap, inputData);
                        }
                    } else if ("order_0e".equals(dataString.toLowerCase())) {  //加密芯片号获取
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_0e(result, loginDto, cookiesMap, json);
                        } else {  //2.0版本对接
                            dealOrder_0e_2(result, loginDto, cookiesMap, json);
                        }
                    } else if ("order_06".equals(dataString.toLowerCase())) {  //通讯模块比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_06(result, loginDto, cookiesMap, map);
                        } else {  //2.0版本对接
                            dealOrder_06_2(result, loginDto, cookiesMap, oldDataDto, map, json);
                        }
                    } else if ("order_08".equals(dataString.toLowerCase())) {  //GPS模块比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_08(result, loginDto, cookiesMap, oldDataDto, map, json);
                        } else {  //2.0版本对接
                            dealOrder_08_2(result, loginDto, cookiesMap, oldDataDto, map, json);
                        }
                    } else if ("order_07".equals(dataString.toLowerCase())) {  //WIFI模块比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_07(result, loginDto, cookiesMap, oldDataDto, map, json);
                        } else {  //2.0版本对接
                            dealOrder_07_2(result, loginDto, cookiesMap, oldDataDto, map, json);
                        }
                    } else if ("order_05".equals(dataString.toLowerCase())) {  //存储容量比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_05(result, loginDto, cookiesMap, oldDataDto, map, json);
                        } else {  //2.0版本对接
                            dealOrder_05_2(result, loginDto, cookiesMap, oldDataDto, map, json);
                        }
                    } else if ("order_03".equals(dataString.toLowerCase())) {  //MAC比较
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_03(result, loginDto, cookiesMap, oldDataDto, map, json, inputData);
                        } else {  //2.0版本对接
                            dealOrder_03_2(result, loginDto, cookiesMap, oldDataDto, map, json, inputData);
                        }
                    } else if ("order_25".equals(dataString.toLowerCase())) {  //SN写入
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_25(result, loginDto, cookiesMap, inputData);
                        } else {  //2.0版本对接
                            dealOrder_25_2(result, loginDto, cookiesMap, inputData);
                        }
                    } else if ("order_01".equals(dataString.toLowerCase())) {  //时区
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_01(result, loginDto, cookiesMap, oldDataDto, map, json);
                        } else {  //2.0版本对接
                            dealOrder_01_2(result, loginDto, cookiesMap, oldDataDto, map, json);
                        }
                    } else if ("order_0a".equals(dataString.toLowerCase())) {  //参数导入
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_0a(result, loginDto, cookiesMap, inputData, map, json);
                        } else {  //2.0版本对接
                            dealOrder_0a_2(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_0b".equals(dataString.toLowerCase())) {  //恢复出厂设置
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_0b(result, loginDto, cookiesMap, inputData, map, json);
                        } else {  //2.0版本对接
                            dealOrder_0b_2(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_0c".equals(dataString.toLowerCase())) {  //机内温度获取
                        System.out.println("==================order_0c=============");
                        if ("1".equals(devVersion)) {  //1.0版本
                            dealOrder_0c(result, loginDto, cookiesMap, inputData, map, json);
                        } else {  //2.0版本对接
                            dealOrder_0c_2(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_termin".equals(dataString)) {
                        System.out.println("==================order_termin=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持终端号读取");
                            return result;
                        } else {
                            dealOrder_order_termin_2(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_date_check".equals(dataString)) {
                        System.out.println("==================order_date_check=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持日期校验");
                            return result;
                        } else {
                            dealOrder_order_date_check_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_time_zone_default".equals(dataString)) {
                        System.out.println("==================order_time_zone_default=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持设置默认时区");
                            return result;
                        } else {
                            dealOrder_time_zone_default_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_time_check_default".equals(dataString)) {
                        System.out.println("==================order_time_check_default=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持设置默认校时");
                            return result;
                        } else {
                            dealOrder_time_check_default_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_acc_check".equals(dataString)) {
                        System.out.println("==================order_acc_check=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持六轴测试");
                            return result;
                        } else {
                            dealOrder_acc_check_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_bluetooth".equals(dataString)) {
                        System.out.println("==================order_bluetooth=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持蓝牙测试");
                            return result;
                        } else {
                            dealOrder_bluetooth(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_2b".equals(dataString)) {
                        System.out.println("==================order_2b=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持TTS状态测试");
                            return result;
                        } else {
                            dealOrder_tts_check(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_26".equals(dataString)) {
                        System.out.println("==================order_26=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持子机型测试");
                            return result;
                        } else {
                            dealOrder_child_machine_check(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_link_net_default".equals(dataString)) {
                        System.out.println("==================order_link_net_default=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持设置默认有线网络");
                            return result;
                        } else {
                            dealOrder_link_net_default_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else if ("order_register_clear".equals(dataString)) {
                        System.out.println("==================order_register_clear=============");
                        if ("1".equals(devVersion)) {
                            result.setCode(500);
                            result.setMsg("老化后【网页版1.0协议】暂不支持清空注册信息");
                            return result;
                        } else {
                            dealOrder_register_clear_02(result, loginDto, cookiesMap, inputData, map, json);
                        }
                    } else {
                        result.setCode(500);
                        result.setMsg("不支持比对,未对接");
                        return result;
                        //原始串口方法
//							dealWithData(frameDto,result,dataString,type,json,map);  //数据发送以及处理，json为扫描输入数据，map为mes后台传来的数据
                    }
                    if (StringUtils.isEmpty(result.getExtend())) {
                        result.setExtend(json.toJSONString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.setCode(500);
                    result.setMsg(e.getMessage());
                    return result;
                }
            } else {
                result.setCode(500);
                result.setMsg("命令出错");
            }
        }
        return result;

    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_order_date_check_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                               String inputData, JSONObject map, JSONObject json) throws Exception {
        String url = loginDto.getVersionUrl() + "systemtime";
        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("获取系统时间失败");
            }

            // 获取响应体
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);

            // 解析 JSON
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);
            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("获取系统时间失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            String systemtime = responseData.getString("systemtime");
            String curdate = map.getString("curdate");
            String devDate = systemtime.substring(0, 10);
            String fillData = "";

            if (devDate.equals(curdate)) {
                fillData += ";IMS服务器日期：" + curdate + "设备日期" + devDate + ";测试成功";
                json.put("devTime", systemtime);
            } else {
                fillData += ";IMS服务器日期：" + curdate + "设备日期" + devDate + ";测试失败";
                throw new RuntimeException(fillData);
            }

            result.setCode(200);
            result.setData(fillData);
            result.setExtend(json.toJSONString());
        } finally {
            // 确保关闭 HttpClient
            httpClient.close();
        }
//		Connection jsuopConnect = Jsoup.connect(url);
//		JsoupUtils.setCookies(jsuopConnect, cookiesMap);
//		String responseStr = jsuopConnect.get().body().html();
//		JSONObject  responseJson = (JSONObject) JSONObject.parse(responseStr);
//		if (responseJson.getInteger("errorcode") != 200) {
//			throw new Exception("获取系统时间失败");
//		}
//		JSONObject responseData = responseJson.getJSONObject("data");
//		String  systemtime = responseData.getString("systemtime");
//		String curdate = map.getString("curdate");
//		String devDate = systemtime.substring(0,10);
//		String fillData = "";
//		if(devDate.equals(curdate)) {
//			fillData+=";IMS服务器日期："+curdate+"设备日期"+ devDate +";测试成功";
//			json.put("devTime",systemtime);
//		}else {
//			fillData+=";IMS服务器日期："+curdate+"设备日期"+ devDate +";测试失败";
//			throw new RuntimeException(fillData);
//		}
//		result.setCode(200);
//		result.setData(fillData);
//		result.setExtend(json.toJSONString());
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_time_zone_default_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                                String inputData, JSONObject map, JSONObject json) throws Exception {
        //获取默认时区设置
        String getDefaultUrl = loginDto.getVersionUrl() + "defaultsystemparam?type=MDVR-TIMEP&pwenc=1";

        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getDefaultUrl);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            // 获取响应体
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);

            // 解析 JSON
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);
            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            JSONObject responseParam = responseData.getJSONObject("PARAMETER");
            JSONObject responseMdvr = responseParam.getJSONObject("MDVR");
            JSONObject responseTimep = responseMdvr.getJSONObject("TIMEP");
            String responseTimez = responseTimep.getString("TIMEZ");
            responseTimep = new JSONObject();
            responseTimep.put("TIMEZ", responseTimez);
            responseMdvr.put("TIMEP", responseTimep);
            System.out.println("设置默认时区：" + responseData.toJSONString());

            // 设置默认时区
            String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
            HttpPost httpPost = new HttpPost(setSysParamUrl);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            // 设置请求体
            httpPost.setEntity(new StringEntity(responseData.toJSONString(), "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse postResponse = httpClient.execute(httpPost)) {
                statusCode = postResponse.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("设置默认时区失败");
                }

                // 获取响应体
                entity = postResponse.getEntity();
                responseStr = EntityUtils.toString(entity);

                // 解析 JSON
                responseJson = (JSONObject) JSONObject.parse(responseStr);
                if (responseJson.getInteger("errorcode") != 200) {
                    throw new Exception("设置默认时区失败");
                }

                String fillData = ";设备默认时区：" + responseTimez + ";设置成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toJSONString());
            }
        } finally {
            // 确保关闭 HttpClient
            httpClient.close();
        }
    }
		/*
		Connection getDefaultConnect = Jsoup.connect(getDefaultUrl);
		JsoupUtils.setCookies(getDefaultConnect, cookiesMap);
		String responseStr = getDefaultConnect.get().body().html();

		JSONObject  responseJson = (JSONObject) JSONObject.parse(responseStr);
		if (responseJson.getInteger("errorcode") != 200) {
			throw new Exception("获取系统默认参数失败");
		}
		JSONObject responseData = responseJson.getJSONObject("data");
		JSONObject responseParam = responseData.getJSONObject("PARAMETER");
		JSONObject responseMdvr = responseParam.getJSONObject("MDVR");
		JSONObject responseTimep = responseMdvr.getJSONObject("TIMEP");
		String responseTimez = responseTimep.getString("TIMEZ");
		responseTimep = new JSONObject();
		responseTimep.put("TIMEZ",responseTimez);
		responseMdvr.put("TIMEP",responseTimep);
		System.out.println("设置默认时区：" + responseData.toJSONString());

		//设置默认时区
		String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
		Connection setSysParamConnnet = Jsoup.connect(setSysParamUrl).method(Connection.Method.POST);
		JsoupUtils.setCookies(setSysParamConnnet, cookiesMap);

		Response response  = setSysParamConnnet.requestBody(responseData.toJSONString()).execute();
		responseStr = response.body();
		responseJson = (JSONObject) JSONObject.parse(responseStr);
		if (responseJson.getInteger("errorcode") != 200) {
			throw new Exception("设置默认时区失败");
		}
		String fillData = ";设备默认时区：" + responseTimez + ";设置成功";
		result.setCode(200);
		result.setData(fillData);
		result.setExtend(json.toJSONString());
	}*/

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_time_check_default_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                                 String inputData, JSONObject map, JSONObject json) throws Exception {
        //获取默认时区设置
        String getDefaultUrl = loginDto.getVersionUrl() + "defaultsystemparam?type=MDVR-ATP&pwenc=1";

        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getDefaultUrl);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }
        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            // 获取响应体
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);

            // 解析 JSON
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);
            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            System.out.println("设置默认校时：" + responseData.toJSONString());

            // 设置默认校时
            String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
            HttpPost httpPost = new HttpPost(setSysParamUrl);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            // 设置请求体
            httpPost.setEntity(new StringEntity(responseData.toJSONString(), "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse postResponse = httpClient.execute(httpPost)) {
                statusCode = postResponse.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("设置默认校时失败");
                }

                // 获取响应体
                entity = postResponse.getEntity();
                responseStr = EntityUtils.toString(entity);

                // 解析 JSON
                responseJson = (JSONObject) JSONObject.parse(responseStr);
                if (responseJson.getInteger("errorcode") != 200) {
                    throw new Exception("设置默认校时失败");
                }

                String fillData = ";设备默认校时：" + responseData.toJSONString() + ";设置成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toJSONString());
            }
        } finally {
            // 确保关闭 HttpClient
            httpClient.close();
        }
		/*
		Connection getDefaultConnect = Jsoup.connect(getDefaultUrl);
		JsoupUtils.setCookies(getDefaultConnect, cookiesMap);
		String responseStr = getDefaultConnect.get().body().html();
		JSONObject  responseJson = (JSONObject) JSONObject.parse(responseStr);
		if (responseJson.getInteger("errorcode") != 200) {
			throw new Exception("获取系统默认参数失败");
		}
		JSONObject responseData = responseJson.getJSONObject("data");
		System.out.println("设置默认校时：" + responseData.toJSONString());

		//设置默认时区
		String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
		Connection setSysParamConnnet = Jsoup.connect(setSysParamUrl).method(Connection.Method.POST);
		JsoupUtils.setCookies(setSysParamConnnet, cookiesMap);
		Response response  = setSysParamConnnet.requestBody(responseData.toJSONString()).execute();
		responseStr = response.body();
		responseJson = (JSONObject) JSONObject.parse(responseStr);
		if (responseJson.getInteger("errorcode") != 200) {
			throw new Exception("设置默认校时失败");
		}
		String fillData = ";设备默认校时：" + responseData.toJSONString() + ";设置成功";
		result.setCode(200);
		result.setData(fillData);
		result.setExtend(json.toJSONString());*/
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_acc_check_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                        String inputData, JSONObject map, JSONObject json) throws Exception {
        //获取六轴测试数据
        String url = loginDto.getVersionUrl() + "checkacc";
        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("第" + map.getString("accCheckNo") + "获取系统默认参数失败");
            }

            // 获取响应体
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);

            // 解析 JSON
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);
            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("第" + map.getString("accCheckNo") + "获取系统默认参数失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            Integer responseAcx = responseData.getInteger("RAM_ACX");
            Integer responseAcy = responseData.getInteger("RAM_ACY");
            Integer responseAcz = responseData.getInteger("RAM_ACZ");
            String accRawXyz = responseAcx + "&" + responseAcy + "&" + responseAcz;
            String fillData = "第" + map.getString("accCheckNo") + "次获取六轴测试数据：" + accRawXyz + ";获取成功";

            // 根据 accCheckNo 决定存储哪个键
            String key = "1".equals(map.getString("accCheckNo")) ? "accRawXyz" : "accRawXyz1";
            json.put(key, accRawXyz);

            result.setCode(200);
            result.setData(fillData);
            result.setExtend(json.toJSONString());
        } finally {
            // 确保关闭 HttpClient
            httpClient.close();
        }
//		Connection jsuopConnect = Jsoup.connect(url);
//		JsoupUtils.setCookies(jsuopConnect, cookiesMap);
//		String responseStr = jsuopConnect.get().body().html();
		/*
		JSONObject  responseJson = (JSONObject) JSONObject.parse(responseStr);
		String accCheckNo = map.getString("accCheckNo");
		if (responseJson.getInteger("errorcode") != 200) {
			throw new Exception("第" + accCheckNo + "获取系统默认参数失败");
		}
		JSONObject responseData = responseJson.getJSONObject("data");
		Integer responseAcx = responseData.getInteger("RAM_ACX");
		Integer responseAcy = responseData.getInteger("RAM_ACY");
		Integer responseAcz = responseData.getInteger("RAM_ACZ");
		String accRawXyz = responseAcx + "&" + responseAcy + "&" + responseAcz;
		String fillData = "第" + accCheckNo + "次获取六轴测试数据：" + accRawXyz + ";获取成功";
		if("1".equals(accCheckNo)){
			json.put("accRawXyz",accRawXyz);
		} else {
			json.put("accRawXyz1",accRawXyz);
		}
		result.setCode(200);
		result.setData(fillData);
		result.setExtend(json.toJSONString());
		*/
    }

    /**
     * author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_bluetooth(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                     String inputData, JSONObject map, JSONObject json) throws Exception {
        String btConnTest = map.getString("btConnTest");
        if ("1".equals(btConnTest)) {
            //打开蓝牙
            String ctrlBluetoothUrl = loginDto.getVersionUrl() + "bluetooth/ctrl?enable=1";
            CloseableHttpClient httpClient = HttpClients.createDefault();

            try (CloseableHttpResponse response = sendGetRequest(httpClient, ctrlBluetoothUrl, cookiesMap)) {
                handleResponse(response, "打开蓝牙失败");
            }
			/*
			String ctrlBluetoothUrl = loginDto.getVersionUrl() + "bluetooth/ctrl?enable=1";
			Connection ctrlBluetoothConnnet = Jsoup.connect(ctrlBluetoothUrl);
			JsoupUtils.setCookies(ctrlBluetoothConnnet, cookiesMap);
			String responseStr = ctrlBluetoothConnnet.get().body().html();
			JSONObject  responseJson = (JSONObject) JSONObject.parse(responseStr);
			if (responseJson.getInteger("errorcode") != 200) {
				throw new Exception("打开蓝牙失败");
			}*/

            // 设置蓝牙名称
            String bluetoothName = map.getString("bluetoothName");
            String setBluetoothNameUrl = loginDto.getVersionUrl() + "bluetooth/set";
            JSONObject requestParam = new JSONObject();
            requestParam.put("name", bluetoothName);
            try (CloseableHttpResponse response = sendPostRequest(httpClient, setBluetoothNameUrl, requestParam, cookiesMap)) {
                handleResponse(response, "设置蓝牙名称失败");
            }

            // 获取蓝牙状态
            String getbluetoothStatus = loginDto.getVersionUrl() + "bluetooth/getstatus";
            try (CloseableHttpResponse response = sendGetRequest(httpClient, getbluetoothStatus, cookiesMap)) {
                handleResponse(response, "获取蓝牙状态失败");
			/*
			String bluetoothName = map.getString("bluetoothName");
			JSONObject requestParam = new JSONObject();
			requestParam.put("name",bluetoothName);
			String setBluetoothNameUrl = loginDto.getVersionUrl() + "bluetooth/set";
			Connection setBluetoothNameConnnet = Jsoup.connect(setBluetoothNameUrl).method(Connection.Method.POST);
			JsoupUtils.setCookies(setBluetoothNameConnnet, cookiesMap);
			Response response  = setBluetoothNameConnnet.requestBody(requestParam.toJSONString()).execute();
			responseStr = response.body();
			responseJson = (JSONObject) JSONObject.parse(responseStr);
			if (responseJson.getInteger("errorcode") != 200) {
				throw new Exception("设置蓝牙名称失败");
			}

			String getbluetoothStatus = loginDto.getVersionUrl() + "bluetooth/getstatus";
			Connection getbluetoothStatusConnnet = Jsoup.connect(getbluetoothStatus);
			JsoupUtils.setCookies(getbluetoothStatusConnnet, cookiesMap);
			responseStr = getbluetoothStatusConnnet.get().body().html();
			responseJson = (JSONObject) JSONObject.parse(responseStr);
			if (responseJson.getInteger("errorcode") != 200) {
				throw new Exception("获取蓝牙状态失败");
			}
			*/
                JSONObject responseJson = parseResponse(response);
                JSONObject responseData = responseJson.getJSONObject("data");
                String devBluetoothName = responseData.getString("devName");
                String fillData = "";
                if (devBluetoothName.equals(bluetoothName)) {
                    fillData = ";蓝牙连接测试成功";
                } else {
                    throw new Exception("蓝牙连接测试失败");
                }
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toJSONString());
            } finally {
                httpClient.close(); // 关闭 HttpClient
            }
        } else {
            result.setCode(200);
            result.setData("未设置连测试测，不检测");
            result.setExtend(json.toJSONString());
        }
    }

    /**
     * @author yulian174
     * 添加GET请求方法和POST请求方法
     */
    private CloseableHttpResponse sendGetRequest(CloseableHttpClient httpClient, String url, Map<String, String> cookiesMap) throws Exception {
        HttpGet httpGet = new HttpGet(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        return httpClient.execute(httpGet);
    }

    /**
     * @author yulian174
     * 添加POST请求方法
     */
    private CloseableHttpResponse sendPostRequest(CloseableHttpClient httpClient, String url, JSONObject body, Map<String, String> cookiesMap) throws Exception {
        HttpPost httpPost = new HttpPost(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        // 设置请求体
        httpPost.setEntity(new StringEntity(body.toJSONString(), "UTF-8"));

        return httpClient.execute(httpPost);
    }

    /**
     * @author yulian174
     * 处理响应
     */
    private void handleResponse(CloseableHttpResponse response, String errorMessage) throws Exception {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new Exception(errorMessage);
        }

        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity);
        JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);
        if (responseJson.getInteger("errorcode") != 200) {
            throw new Exception(errorMessage);
        }
    }

    /**
     * @author yulian174
     * 解析响应JSON
     */
    private JSONObject parseResponse(CloseableHttpResponse response) throws Exception {
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity);
        return (JSONObject) JSONObject.parse(responseStr);
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_tts_check(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                     String inputData, JSONObject map, JSONObject json) throws Exception {
        String ttslicenseUrl = loginDto.getVersionUrl() + "ttslicense";
        // 使用 HttpClient 发送请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(ttslicenseUrl);
        /*
        Connection submachinetypeConnnet = Jsoup.connect(submachinetypeUrl);
        JsoupUtils.setCookies(submachinetypeConnnet, cookiesMap);
        String responseStr = submachinetypeConnnet.get().body().html();
        */
        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);

            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("TTS授权状态查询失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            Integer ttsStatus = responseData.getInteger("status");
            String fillData = "";

            if ("1".equals(ttsStatus.toString())) {
                fillData = ";TTS授权成功";
            } else {
                if ("0".equals(ttsStatus.toString())) {
                    throw new Exception("TTS授权未初始化");
                } else {
                    throw new Exception("TTS授权初始化失败");
                }
            }

            result.setCode(200);
            result.setData(fillData);
            result.setExtend(json.toJSONString());
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_child_machine_check(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                               String inputData, JSONObject map, JSONObject json) throws Exception {
        String submachinetypeUrl = loginDto.getVersionUrl() + "getsubmachinetype";
        /*Connection submachinetypeConnnet = Jsoup.connect(submachinetypeUrl);
        JsoupUtils.setCookies(submachinetypeConnnet, cookiesMap);
        String responseStr = submachinetypeConnnet.get().body().html();*/
        // 使用 HttpClient 发送请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(submachinetypeUrl);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);

            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("子机型信息查询失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            JSONObject responseCmdline = responseData.getJSONObject("cmdline");
            Integer devMachineType = responseCmdline.getInteger("MachineType");
            String machineType = map.getString("value");
            String fillData = "";

            if (machineType.equals(devMachineType.toString())) {
                json.put("childMachineType", String.valueOf(devMachineType));
                fillData += ";：工单设置子机型" + machineType + "设备子机型" + devMachineType + ";测试成功";
            } else {
                fillData += ";：工单设置子机型" + machineType + "设备子机型" + devMachineType + ";测试失败";
                throw new RuntimeException(fillData);
            }

            result.setCode(200);
            result.setData(fillData);
            result.setExtend(json.toJSONString());
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_link_net_default_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                               String inputData, JSONObject map, JSONObject json) throws Exception {
        //获取默认有线网络设置
        String getDefaultUrl = loginDto.getVersionUrl() + "defaultsystemparam?type=MDVR-ETHERNET&pwenc=1";
        /*Connection getDefaultConnect = Jsoup.connect(getDefaultUrl);
        JsoupUtils.setCookies(getDefaultConnect, cookiesMap);
        String responseStr = getDefaultConnect.get().body().html();*/
        // 使用 HttpClient 发送 GET 请求获取默认有线网络设置
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getDefaultUrl);
        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);

            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            System.out.println("设置默认有线网络：" + responseData.toJSONString());

            // 使用 HttpClient 发送 POST 请求来设置默认有线网络
            String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
            HttpPost httpPost = new HttpPost(setSysParamUrl);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            httpPost.setEntity(new StringEntity(responseData.toJSONString(), "UTF-8"));
            httpPost.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse postResponse = httpClient.execute(httpPost)) {
                statusCode = postResponse.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("HTTP request failed with status code: " + statusCode);
                }

                HttpEntity postEntity = postResponse.getEntity();
                responseStr = EntityUtils.toString(postEntity);
                responseJson = (JSONObject) JSONObject.parse(responseStr);

                if (responseJson.getInteger("errorcode") != 200) {
                    throw new Exception("设置默认有线网络失败");
                }

                String fillData = ";设备默认有线网络：" + responseData.toJSONString() + ";设置成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toJSONString());
            }
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_register_clear_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                             String inputData, JSONObject map, JSONObject json) throws Exception {
        //获取默认注册信息
        String getDefaultUrl = loginDto.getVersionUrl() + "defaultsystemparam?type=MDVR-RIP,MDVR-VS,MDVR-PS,MDVR-PSI&pwenc=1";
        /*
        Connection getDefaultConnect = Jsoup.connect(getDefaultUrl);
        JsoupUtils.setCookies(getDefaultConnect, cookiesMap);
        String responseStr = getDefaultConnect.get().body().html();*/
        // 使用 HttpClient 发送 GET 请求获取默认注册信息
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getDefaultUrl);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);
            JSONObject responseJson = (JSONObject) JSONObject.parse(responseStr);

            if (responseJson.getInteger("errorcode") != 200) {
                throw new Exception("获取系统默认参数失败");
            }

            JSONObject responseData = responseJson.getJSONObject("data");
            System.out.println("设置默认注册信息：" + responseData.toJSONString());

            // 使用 HttpClient 发送 POST 请求来设置默认注册信息
            String setSysParamUrl = loginDto.getVersionUrl() + "systemparam";
            HttpPost httpPost = new HttpPost(setSysParamUrl);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            httpPost.setEntity(new StringEntity(responseData.toJSONString(), "UTF-8"));
            httpPost.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse postResponse = httpClient.execute(httpPost)) {
                statusCode = postResponse.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("HTTP request failed with status code: " + statusCode);
                }

                HttpEntity postEntity = postResponse.getEntity();
                responseStr = EntityUtils.toString(postEntity);
                responseJson = (JSONObject) JSONObject.parse(responseStr);

                if (responseJson.getInteger("errorcode") != 200) {
                    throw new Exception("设置默认注册信息失败");
                }

                String fillData = ";设备默认注册信息：" + responseData.toJSONString() + ";设置成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toJSONString());
            }
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }


    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_0c_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                String inputData, JSONObject map, JSONObject json) throws IOException {
        String fillData = "";
        String url = loginDto.getVersionUrl() + "deviceenvironment";
        /*
        Connection verConnect = Jsoup.connect(url);
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();*/
        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String verData = EntityUtils.toString(entity);
            JSONObject parse = (JSONObject) JSONObject.parse(verData);
            JSONObject data = parse.getJSONObject("data");
            JSONObject temperature = data.getJSONObject("temperature");
            String temperatureValue = temperature.getString("RT1");
            temperatureValue = temperatureValue.substring(0, temperatureValue.length() - 2); // 最后两位截取掉

            json.put("temperatureValue", temperatureValue);
            fillData = "===>获取机内温度数据：" + temperatureValue + ";测试成功";
            result.setCode(200);
            result.setData(fillData);
            result.setExtend(json.toString());
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_order_termin_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap, String inputData, JSONObject map, JSONObject json) throws Exception {
        /*
        Connection macConnect = Jsoup.connect(loginDto.getVersionUrl() + "systemparam?type=MDVR-KEYS,MDVR-PSI-PI-0-TID");
        JsoupUtils.setCookies(macConnect, cookiesMap);
        Document macDocument = macConnect.get();
        String macData = macDocument.body().html();*/
        String url = loginDto.getVersionUrl() + "systemparam?type=MDVR-KEYS,MDVR-PSI-PI-0-TID";

        // 使用 HttpClient 发送 GET 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        // 设置 Cookies
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("HTTP request failed with status code: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            String macData = EntityUtils.toString(entity);
            JSONObject macParse = (JSONObject) JSONObject.parse(macData);
            JSONObject dataObject = macParse.getJSONObject("data");
            JSONObject mdvrObject = dataObject.getJSONObject("PARAMETER").getJSONObject("MDVR");
            JSONObject psiObject = mdvrObject.getJSONObject("PSI");
            String terminalId = "";

            if (psiObject != null) {
                JSONArray piArray = psiObject.getJSONArray("PI");
                for (Object pi : piArray) {
                    String tid = ((JSONObject) pi).getString("TID");
                    if (null != tid) {
                        terminalId = tid;
                    }
                }
            }

            if ("".equals(terminalId)) {
                result.setCode(500);
                result.setMsg("老化后【网页版2.0协议】终端号没有读取");
            } else {
                json.put("terminalNo", terminalId);
                String fillData = "===>获取终端号：" + terminalId + ";测试成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toString());
            }
        } finally {
            httpClient.close(); // 关闭 HttpClient
        }
    }


    private void dealOrder_0c(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              String inputData, JSONObject map, JSONObject json) {
        result.setCode(500);
        result.setMsg("未对接");
    }


    private void dealOrder_25_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                String inputData) {
        // TODO 自动生成的方法存根

    }


    private void dealOrder_03_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json, String inputData) throws Exception {
        mesIpcService.getDevMac2(loginDto, cookiesMap, oldDataDto);
        String mac = inputData.replaceAll(":", "").replaceAll("：", "").replaceAll("-", "").toUpperCase();
        String clearMac = oldDataDto.getMac().replaceAll(":", "").replaceAll("：", "").replaceAll("-", "").toUpperCase();
        String fillData = "===> 设备MAC地址：" + clearMac;
        if (clearMac.equals(mac)) {
            fillData += ";测试成功";
            json.put("macAddress", mac);
        } else {
            fillData += ";输入的mac地址：" + mac + ";测试失败";
            throw new RuntimeException(fillData);
        }
        result.setCode(200);
        result.setData(fillData);
        result.setExtend(json.toJSONString());
    }


    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_01_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        String finalData = null;
        String timeZone = map.getString("timeArea");
        if (StringUtils.isBlank(timeZone)) {
            throw new Exception("时区校验出错，交互配置未配置时区");
        }
        String timez = "";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String url = loginDto.getVersionUrl() + "systemparam?type=MDVR-TIMEP";
            HttpGet httpGet = new HttpGet(url);
            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }
            /*
            Connection verConnect = Jsoup.connect(url);
            JsoupUtils.setCookies(verConnect, cookiesMap);
            Document verDocument = verConnect.get();
            String verData = verDocument.body().html();*/
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("HTTP request failed with status code: " + statusCode);
                }

                HttpEntity entity = response.getEntity();
                String verData = EntityUtils.toString(entity);
                JSONObject parse = (JSONObject) JSONObject.parse(verData);
                JSONObject data = parse.getJSONObject("data");
                JSONObject parameter = data.getJSONObject("PARAMETER");
                JSONObject mdvr = parameter.getJSONObject("MDVR");
                JSONObject timep = mdvr.getJSONObject("TIMEP");
                timez = timep.getString("TIMEZ");
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("获取时区出错：" + e.getMessage());
            }
            Integer time = 0;
            try {
                time = Integer.valueOf(timez.substring(0, timez.length() - 1));
            } catch (Exception e) {
                throw new Exception("获取时区转换失败：" + timez.substring(0, timez.length() - 1) + "，错误信息：" + e.getMessage());
            }
            time = time / 60;
            if (!timeZone.equals(time + "")) {
                throw new Exception("时区校验出错，工单获取时区：" + timeZone + ",配置设备时区：" + time);
            }
            // 获取设备时间
            String urlForTime = loginDto.getVersionUrl() + "systemtime";
            HttpGet httpGetForTime = new HttpGet(urlForTime);
            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGetForTime.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }
            try (CloseableHttpResponse response = httpClient.execute(httpGetForTime)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new Exception("HTTP request failed with status code: " + statusCode);
                }

                HttpEntity entity = response.getEntity();
                String date = EntityUtils.toString(entity);
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime of = LocalDateTime.parse(date, df);
                LocalDateTime now = LocalDateTime.now();
                Duration duration = Duration.between(now, of);
                long minutes = duration.toMinutes();
                if (minutes > 3 || minutes < -3) {
                    throw new Exception("时间校验出错，本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                            "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes);
                }
                String timeString = "===>本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                        "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes;

                finalData = "===> 设备时区：" + time + "，工单配置时区：" + timeZone + ";" + timeString + ";测试成功";

                json.put("timeArea", String.valueOf(time));
                json.put("machineDate", of);
                result.setCode(200);
                result.setData(finalData);
                result.setExtend(json.toJSONString());
            }
        /*
        try {
            String url = loginDto.getVersionUrl() + "systemtime";
            Connection verConnect = Jsoup.connect(url);
            JsoupUtils.setCookies(verConnect, cookiesMap);
            Document verDocument = verConnect.get();
            String verData = verDocument.body().html();
            JSONObject parse = (JSONObject) JSONObject.parse(verData);
            JSONObject data = parse.getJSONObject("data");
            date = data.getString("systemtime");
        } catch (Exception e) {
            throw new Exception("获取设备时间出错：" + e.getMessage());
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime of = LocalDateTime.parse(date, df);
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(now, of);
        long minutes = duration.toMinutes();
        if (minutes > 3 || minutes < -3) {
            throw new Exception("时间校验出错，本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                    "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes);
        }
        String timeString = "===>本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes;

        finalData = "===> 设备时区：" + time + "，工单配置时区：" + timeZone + ";" + timeString + ";测试成功";

        json.put("timeArea", String.valueOf(time));
        json.put("machineDate", of);
        result.setCode(200);
        result.setData(finalData);
        result.setExtend(json.toJSONString());*/
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_0e_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                JSONObject json) throws IOException {
        String fillData = "";
        String url = loginDto.getVersionUrl() + "systemconfig";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new IOException("HTTP request failed with status code: " + statusCode);
                }

                HttpEntity entity = response.getEntity();
                String verData = EntityUtils.toString(entity);
                JSONObject parse = (JSONObject) JSONObject.parse(verData);
                JSONObject data = parse.getJSONObject("data");
                String serial = data.getString("securitynum");
                json.put("chipNumber", serial);
                fillData = "===>获取加密芯片号数据：" + serial + ";测试成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toString());
            }
        }
        /*
        Connection verConnect = Jsoup.connect(url);
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();
        JSONObject parse = (JSONObject) JSONObject.parse(verData);
        JSONObject data = parse.getJSONObject("data");
        String serial = data.getString("securitynum");
        json.put("chipNumber", serial);
        fillData = "===>获取加密芯片号数据：" + serial + ";测试成功";
        result.setCode(200);
        result.setData(fillData);
        result.setExtend(json.toString());*/
    }


    private void dealOrder_1c_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                String inputData) throws Exception {
        // TODO 自动生成的方法存根
        result.setCode(500);
        result.setMsg("未对接");
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_0b_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                String inputData, JSONObject map, JSONObject json) throws IOException {
        String url = loginDto.getVersionUrl() + "restorefactorysettings";
        /*
        Connection verConnect = Jsoup.connect(url);
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();*/
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new IOException("HTTP request failed with status code: " + statusCode);
                }

                // 注意：这里没有使用响应体，因此不需要读取实体
                result.setCode(200);
                result.setData("恢复出厂设置成功");
            }
        }
        long startTime = System.currentTimeMillis();
        requestLog(loginDto.getVersionUrl() + "log", "Factory Data Reset", cookiesMap);
        long endTime = System.currentTimeMillis();
        System.out.println("2.0耗时：" + (endTime - startTime));
        try {
            Thread.currentThread().sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    //1.0版本恢复出厂设置
    private void dealOrder_0b(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              String inputData, JSONObject map, JSONObject json) throws IOException {
//		result.setCode(500);
//		result.setMsg("未对接");
        String url = loginDto.getVersionUrl() + "?opt=sys&cmd=restore";
        /*
        Connection verConnect = Jsoup.connect(url);
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        result.setCode(200);
        result.setData("恢复出厂设置成功");*/
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new IOException("HTTP request failed with status code: " + statusCode);
                }

                // 注意：这里没有使用响应体，因此不需要读取实体
                result.setCode(200);
                result.setData("恢复出厂设置成功");
            }
        }
        requestLog(loginDto.getVersionUrl() + "log", "Factory Data Reset", cookiesMap);
        try {
            Thread.currentThread().sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String compareMemory(JSONObject configData, JSONObject storageData, List<MemoryDto> memoryDtoList, Long deviceCount, Long configCount, String fillData) throws Exception {
        MemoryDto memoryDto = null;
        Integer internal = storageData.getInteger("internal");
        long left = storageData.getLongValue("left");
        long total = storageData.getLongValue("totle");
        if (left > 0 || total > 0) {
            deviceCount++;
        }
        left = left / (1000 * 1000 * 1000);
        total = total / (1000 * 1000 * 1000);
        Integer number = storageData.getInteger("id");
        Integer type = storageData.getInteger("type");
        String typeName = "";
        String configName = "";
        if (type == 0 && internal == 0) {
            typeName = "自带硬盘";
            configName = "memoryCheckOne";
        }
        if (type == 0 && internal != 0) {
            typeName = "外置硬盘";
            configName = "memoryCheckSix";
        }
        if (type == 1 && internal == 0) {
            typeName = "内置SD卡（内置镜像）";
            configName = "memoryCheckTwo";
        }
        if (type == 1 && internal != 0) {
            typeName = "外置SD卡（外置镜像）";
            configName = "memoryCheckThree";
        }
        if (type == 2) {
            typeName = "U口";
            configName = "memoryCheckFive";
        }

        if (configData.containsKey(configName) || configData.containsKey(configName + "Total")) {
            configCount++;
        }
        String testData = "";
        int testResult = 0;
        if (configData.containsKey(configName)) {
            String[] split = configData.getString(configName).split("#");
            double min = Double.parseDouble(split[0]);
            double max = Double.parseDouble(split[1]);
            if (min <= left && left <= max) {
                testResult += 1;
                memoryDto = new MemoryDto();
                memoryDto.setMemoryNo(number);
                memoryDto.setMemoryType(internal);
                memoryDto.setMemoryLeft(left);
                testData = "编号：" + number + ";类型：" + typeName;
                testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";";
            } else {
                testResult -= 1;
                testData = "编号：" + number + ";类型：" + typeName;
                testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";";
            }
        }
        if (configData.containsKey(configName + "Total")) {
            Double configTotal = Double.parseDouble(configData.getString(configName + "Total"));
            if (configTotal <= total) {
                testResult += 1;
                if (memoryDto == null) {
                    memoryDto = new MemoryDto();
                }
                memoryDto.setMemoryTotal(total);
                if (StringUtils.isBlank(testData)) {
                    testData = "编号：" + number + ";类型：" + typeName;
                }
                testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + ";";
            } else {
                testResult -= 1;
                if (StringUtils.isBlank(testData)) {
                    testData = "编号：" + number + ";类型：" + typeName;
                }
                testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + ";";
            }
        }
        fillData += testData;
        //比对规则，剩余容量和 总容量成功一个即认为是成功
        if (testResult < 0) {
            throw new Exception(fillData + "测试失败！");
        }
        if (memoryDto != null) {
            memoryDtoList.add(memoryDto);
        }
        return fillData;
    }

    private void dealOrder_05(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getStorageDev(loginDto, cookiesMap, oldDataDto);
        String fillData = "";
        List<MemoryDto> memoryDtoList = new ArrayList<>();
        Long deviceCount = 0L;
        Long configCount = 0L;
        for (int i = 0; i < oldDataDto.getStorage().size(); i++) {
            JSONObject storageData = oldDataDto.getStorage().getJSONObject(i);
            System.out.println("===========================");
            fillData = compareMemory(map, storageData, memoryDtoList, deviceCount, configCount, fillData);
            System.out.println(i);
            System.out.println(storageData);
            System.out.println(fillData);
            System.out.println("===========================");
        }
        if (configCount > deviceCount) {
            fillData += "===> 存储设备测试数量：" + configCount + "；存储设备实际数量：" + deviceCount + "；比对结果：大于;测试失败！";
            throw new Exception(fillData);
        }

        json.put("memorySum", deviceCount);
        json.put("list", memoryDtoList);
        fillData += "测试成功";

//		String finalDataString = FrameUtil.dealOrder_05_new(oldDataDto.getStorage(),oldDataDto.getUseStorage(), map, json);

        result.setCode(200);
        result.setData(fillData);
        result.setExtend(json.toJSONString());
    }


    private String compareMemory_2(JSONObject configData, JSONObject storageData, List<MemoryDto> memoryDtoList, Long deviceCount, Long configCount, String fillData) throws Exception {
        MemoryDto memoryDto = null;
        Integer internal = storageData.getInteger("position");
        long left = storageData.getLongValue("freeSize");
        long total = storageData.getLongValue("totalSize");
        if (left > 0 || total > 0) {
            deviceCount++;
        }
        left = left / (1000 * 1000 * 1000);
        total = total / (1000 * 1000 * 1000);
        Integer number = storageData.getInteger("devId");
        Integer type = storageData.getInteger("devType");
        String typeName = "";
        String configName = "";
        if (type == 2 && internal == 0) {
            typeName = "自带硬盘";
            configName = "memoryCheckOne";
        }
        if (type == 2 && internal != 0) {
            typeName = "外置硬盘";
            configName = "memoryCheckSix";
        }
        if (type == 1 && internal == 0) {
            typeName = "内置SD卡（内置镜像）";
            configName = "memoryCheckTwo";
        }
        if (type == 1 && internal != 0) {
            typeName = "外置SD卡（外置镜像）";
            configName = "memoryCheckThree";
        }
        if (type == 0) {
            typeName = "U口";
            configName = "memoryCheckFive";
        }

        if (configData.containsKey(configName) || configData.containsKey(configName + "Total")) {
            configCount++;
        }
        String testData = "";
        int testResult = 0;
        if (configName.equals("memoryCheckTwo")) {
            if (number == 0) {
                if (configData.containsKey(configName)) {
                    String[] split = configData.getString(configName).split("#");
                    double min = Double.parseDouble(split[0]);
                    double max = Double.parseDouble(split[1]);
                    if (min <= left && left <= max) {
                        testResult += 1;
                        memoryDto = new MemoryDto();
                        memoryDto.setMemoryNo(number);
                        memoryDto.setMemoryType(internal);
                        memoryDto.setMemoryLeft(left);
                        testData = "编号：" + number + ";类型：" + typeName;
                        testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";剩余容量测试成功！";
                    } else {
                        testResult -= 1;
                        testData = "编号：" + number + ";类型：" + typeName;
                        testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";";
                    }
                }
            }
            if (number == 1) {
                if (configData.containsKey(configName + "Total")) {
                    Double configTotal = Double.parseDouble(configData.getString(configName + "Total"));
                    if (configTotal <= total && total <= (configTotal + 6)) {
                        testResult += 1;
                        if (memoryDto == null) {
                            memoryDto = new MemoryDto();
                        }
                        memoryDto.setMemoryTotal(total);
                        if (StringUtils.isBlank(testData)) {
                            testData = "编号：" + number + ";类型：" + typeName;
                        }
                        testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + "；总容量设置上限：" + (configTotal + 6) + "; 总容量测试成功！";
                    } else {
                        testResult -= 1;
                        if (StringUtils.isBlank(testData)) {
                            testData = "编号：" + number + ";类型：" + typeName;
                        }
                        testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + "；总容量设置上限：" + (configTotal + 6) + ";";
                    }
                }
            }
        } else {
            if (configData.containsKey(configName)) {
                String[] split = configData.getString(configName).split("#");
                double min = Double.parseDouble(split[0]);
                double max = Double.parseDouble(split[1]);
                if (min <= left && left <= max) {
                    testResult += 1;
                    memoryDto = new MemoryDto();
                    memoryDto.setMemoryNo(number);
                    memoryDto.setMemoryType(internal);
                    memoryDto.setMemoryLeft(left);
                    testData = "编号：" + number + ";类型：" + typeName;
                    testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";剩余容量测试成功！";
                } else {
                    testResult -= 1;
                    testData = "编号：" + number + ";类型：" + typeName;
                    testData += "；剩余容量：" + left + "；剩余容量设置范围：" + min + "~" + max + ";";
                }
            }
            if (configData.containsKey(configName + "Total")) {
                Double configTotal = Double.parseDouble(configData.getString(configName + "Total"));
                if (configTotal <= total) {
                    testResult += 1;
                    if (memoryDto == null) {
                        memoryDto = new MemoryDto();
                    }
                    memoryDto.setMemoryTotal(total);
                    if (StringUtils.isBlank(testData)) {
                        testData = "编号：" + number + ";类型：" + typeName;
                    }
                    testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + "; 总容量测试成功！";
                } else {
                    testResult -= 1;
                    if (StringUtils.isBlank(testData)) {
                        testData = "编号：" + number + ";类型：" + typeName;
                    }
                    testData += "；总容量：" + total + "；总容量设置下限：" + configTotal + ";";
                }
            }
        }

        fillData += testData;
        if (testResult < 0) {
            throw new Exception(fillData + "测试失败！");
        }
        if (memoryDto != null) {
            memoryDtoList.add(memoryDto);
        }
        return fillData;
    }

    private void dealOrder_05_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getStorageDev2(loginDto, cookiesMap, oldDataDto);
        String fillData = "";
        List<MemoryDto> memoryDtoList = new ArrayList<>();
        Long deviceCount = 0L;
        Long configCount = 0L;

        for (int i = 0; i < oldDataDto.getStorage().size(); i++) {
            JSONObject storageData = oldDataDto.getStorage().getJSONObject(i);
            fillData = compareMemory_2(map, storageData, memoryDtoList, deviceCount, configCount, fillData);
        }
        if (configCount > deviceCount) {
            fillData += "===> 存储设备测试数量：" + configCount + "；存储设备实际数量：" + deviceCount + "；比对结果：大于;测试失败！";
            throw new Exception(fillData);
        }

        json.put("memorySum", deviceCount);
        json.put("list", memoryDtoList);
        fillData += "测试成功";


//		String finalDataString = FrameUtil.dealOrder_05_new2(oldDataDto.getStorage(), oldDataDto.getUseStorage(), map, json);
        result.setCode(200);
        result.setData(fillData);
        result.setExtend(json.toJSONString());
    }

    private void dealOrder_0a_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                String inputData, JSONObject map, JSONObject json) throws IOException {
        inputData = "config";
        String cookies = JsoupUtils.setCookies(cookiesMap);
        String importPath = map.getString("importPath");
        if (StringUtils.isBlank(importPath)) {
            result.setCode(500);
            result.setMsg("参数导入路径为空");
        }
        importPath = importPath.replaceAll("/", Matcher.quoteReplacement(File.separator)).replaceAll("\\\\", Matcher.quoteReplacement(File.separator));
        String path = importPath + File.separator + inputData;
        HttpClientUtil.doPostCookies2(result, loginDto.getUploadUrl(), cookies, path);
        if (result.getCode().equals(200)) { //写日志
            requestLog(loginDto.getVersionUrl() + "log", "Import Parameters", cookiesMap);
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void requestLog(String url, String log, Map<String, String> cookiesMap) {
//        try {
//            Map<String, String> paramMap = new HashMap<>();
//            paramMap.put("uid", "admin");
//            paramMap.put("log", log);
//            Jsoup.connect(url).data(paramMap).cookies(cookiesMap).method(Connection.Method.POST).execute();
//        } catch (Exception e) {
//            // 设备日志接口有可能报400错误
//        }
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("uid", "admin");
            paramMap.put("log", log);

            JSONObject jsonObject = new JSONObject();
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(url);

                // 设置 Cookies
                for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                    httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
                }

                // 设置 POST 参数
                StringEntity params = new StringEntity(jsonObject.toString(), "UTF-8");
                httpPost.setEntity(params);
                httpPost.setHeader("Content-type", "application/json");

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode != 200) {
                        // 可以在这里记录错误状态码或进行其他处理
                    }
                    // 注意：这里没有使用响应体，因此不需要读取实体
                }
            }
        } catch (IOException e) {
            // 设备日志接口有可能报400错误
        }
    }


    private void dealOrder_07_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        String dataString = mesIpcService.setWifiMode(loginDto, cookiesMap, map, json);
        mesIpcService.getDevInfo2(loginDto, cookiesMap, oldDataDto, 0);
        String value = map.getString("value");
        System.out.printf("debug581: {%s}", value);
        String[] split = value.split("#");
        String signal = oldDataDto.getSignal();
        if (split.length == 1) {
            Integer signalInt = 0;
            Integer signalInt1 = 0;
            try {
                signalInt = Integer.valueOf(signal);
                signalInt1 = Integer.valueOf(value);
            } catch (Exception e) {
                throw new Exception("WIFI模块信号强度转换异常:" + e.getMessage());
            }
            if (signalInt >= signalInt1) {
                dataString += "===> 本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度：" + signalInt1 + ",对比结果：大于等于;";
                json.put("chatSignal", signalInt);
            } else {
                dataString += "===> 信号强度不正确;本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度：" + signalInt1 + ",对比结果：小于;";
                throw new Exception(dataString);
            }
        } else {
            String limitString = "";
            Integer signalInt = 0;
            Integer signalInt1 = 0;
            Integer signalInt2 = 0;
            try {
                signalInt = Integer.valueOf(signal);
                signalInt1 = Integer.valueOf(split[0]);
                signalInt2 = Integer.valueOf(split[1]);
            } catch (Exception e) {
                System.out.printf("debug610: {%s}-{%s}-{%s}", signal, split[0], split[1]);
                throw new Exception("WIFI模块信号强度转换异常:" + e.getMessage());
            }
            limitString = "(" + signalInt1 + "~" + signalInt2 + ")";
            if (signalInt >= signalInt1 && signalInt <= signalInt2) {

                dataString += "===> 本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度设置范围：" + limitString + ";";
                json.put("chatSignal", signalInt);
            } else {
                dataString += "===> 信号强度不正确;本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度设置范围：" + limitString + ",对比结果：小于下限或大于上限;测试失败！";
                throw new Exception(dataString);
            }
        }
        if (json.getInteger("chatSignal") == 0) {
            json.put("wifiLinkStatus", 0);
            dataString += "===>WIFI连接状态：未连接;";
        } else {
            json.put("wifiLinkStatus", 1);
            dataString += "===>WIFI连接状态：连接成功;";
        }
        json.put("wifiMac", oldDataDto.getWifiMac());
        dataString += "===>WIFI MAC地址：" + oldDataDto.getWifiMac() + ";";
        json.put("wifiIp", oldDataDto.getWifiIp());
        dataString += "===>IP地址：" + oldDataDto.getWifiIp() + ";";
        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());
    }

    private void dealOrder_08_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getDevInfo2(loginDto, cookiesMap, oldDataDto, 0);
        mesIpcService.getVersion2(loginDto, cookiesMap, oldDataDto);
        String dataString = "";
        if (StringUtils.isNotBlank(map.getString("gpsSum"))) {//工单未维护的不比对，直接通过
            Integer gpsSum1 = 0;
            Integer gpsSum = 0;
            try {
                gpsSum1 = Integer.parseInt(map.getString("gpsSum"));
                gpsSum = Integer.parseInt(oldDataDto.getGpsSum());
            } catch (Exception e) {
                throw new Exception("GPS模块卫星颗数转换数字类型失败：" + e.getMessage());
            }
            if (gpsSum >= gpsSum1) {
                dataString += "===> 本机GPS模块卫星颗数：" + gpsSum + ",工单获取GPS模块卫星颗数：" + gpsSum1 + ",对比结果：大于等于;";
                json.put("gpsSatellite", gpsSum);
            } else {
                dataString += "===> 本机GPS模块卫星颗数：" + gpsSum + ",工单获取GPS模块卫星颗数：" + gpsSum1 + ",对比结果：小于;";
                throw new Exception(dataString);
            }
        }
        if (StringUtils.isNotBlank(map.getString("gpsVersion"))) {//工单未维护的不比对，直接通过
            String gpsVersion1 = map.getString("gpsVersion");
            String gpsVersion = oldDataDto.getGpsVersion();

            if (StringUtils.isBlank(gpsVersion)) {
                dataString += "===> 交互配置勾选了比对版本号，机器未获取到版本号！";
                throw new Exception(dataString);
            }
            if (StringUtils.isNotEmpty(gpsVersion1) && gpsVersion.contains(gpsVersion1)) { //模糊比对
                dataString += "===> 本机GPS模块版本：" + gpsVersion + ",工单获取GPS模块版本：" + gpsVersion1 + ",对比结果：相同;";
                json.put("gpsSoftVersion", gpsVersion);
            } else {
                dataString += "===> 本机GPS模块版本：" + gpsVersion + ",工单获取GPS模块版本：" + gpsVersion1 + ",对比结果：不同;";
                throw new Exception(dataString);
            }
        }
        json.put("gpsLinkStatus", oldDataDto.getGpsStatus() == 0 ? 1 : 0);//S
        String statuString = oldDataDto.getGpsStatus() == 0 ? "连接成功" : "未连接";
        dataString += "===>GPS连接状态：" + statuString + ";";
        json.put("gpsModelType", 0);  //未知,待定
        dataString += "===>GPS类型：GPS;";
        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());

    }

    private void dealOrder_06_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getDevInfo2(loginDto, cookiesMap, oldDataDto, 1);
        String dataString = "";
        if (StringUtils.isNotBlank(map.getString("chatVersion"))) {//工单未维护的不比对，直接通过
            String sver1 = map.getString("chatVersion");
            String sver = oldDataDto.getSver();
            String[] sverArr = sver1.split("_");
            if (sverArr != null && sverArr.length > 0) {
                boolean flag = true;
                for (String arr : sverArr) {
                    if (StringUtils.isNotBlank(sver) && sver.contains(arr)) { //模糊比对
                        flag = true;
                    } else {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    dataString += "===> 本机通讯模块版本号：" + sver + ",工单获取通讯模块版本号：" + sver1 + ",对比结果：相同;";
                    json.put("chatVersion", sver);
                } else {
                    dataString += "===> 本机通讯模块版本号：" + sver + ",工单获取通讯模块版本号：" + sver1 + ",对比结果：不同;";
                    throw new Exception(dataString);
                }
            } else {
                dataString += "===> 本机通讯模块版本号：" + sver + ",工单获取通讯模块版本号：" + sver1 + ",对比结果：不同;";
                throw new Exception(dataString);
            }
        }
        if (StringUtils.isNotBlank(map.getString("chatSignal"))) {//工单未维护的不比对，直接通过
            //工单未维护的不比对，直接通过
            String si1 = map.getString("chatSignal");
            String[] split = si1.split("#");
            String si = oldDataDto.getSi();
            String sr = oldDataDto.getSr();
            if (split.length == 1) {
                Integer signalInt = 0;
                Integer signalInt1 = 0;
                try {
                    signalInt = Integer.valueOf(si);
                    signalInt1 = Integer.valueOf(si1);
                } catch (Exception e) {
                    throw new Exception("===> 信号强度转换失败,测试信号强度失败:" + e.getMessage());
                }
                if (signalInt >= signalInt1) {
                    dataString += "===> 本机通讯模块信号强度：" + si + ",工单获取通讯模块信号强度：" + si1 + ",对比结果：大于等于;";
                    json.put("chatSignal", si);
                } else {
                    dataString += "===> 本机通讯模块信号强度：" + si + ",工单获取通讯模块信号强度：" + si1 + ",对比结果：小于;";
                    throw new Exception(dataString);
                }
            } else {
                String limitString = "";
                Integer signalInt = 0;
                Integer signalInt1 = 0;
                Integer signalInt2 = 0;
                try {
                    signalInt = Integer.valueOf(sr);
                    signalInt1 = Integer.valueOf(split[0]);
                    signalInt2 = Integer.valueOf(split[1]);
                } catch (Exception e) {
                    throw new Exception("===> 信号强度转换失败,测试信号强度失败:" + e.getMessage());
                }
                limitString = "(" + signalInt1 + "~" + signalInt2 + ")";
                if ((signalInt > signalInt1 && signalInt < signalInt2) || signalInt.equals(signalInt1) || signalInt.equals(signalInt2)) {
                    dataString += "===> 本机通讯模块信号强度：" + signalInt + ",工单获取通讯模块信号强度设置范围：" + limitString + ";";
                    json.put("chatSignal", signalInt);
                } else {
                    dataString += "===> 信号强度不正确;本机通讯模块信号强度：" + signalInt + ",工单获取通讯模块信号强度设置范围：" + limitString + ",对比结果：小于等于;测试失败！";
                    throw new Exception(dataString);
                }
            }
        }
        //通讯模块类型
        Integer chatType = Integer.parseInt(map.getString("chatType"));
        String modelTypeString = FrameUtil.getChatModelType(oldDataDto.getNt() + 1);
        String setTypeString = FrameUtil.getChatModelType(chatType);
        System.out.println("\n\n=====chatType=" + chatType + ";modelTypeString=" + modelTypeString + ";setTypeString=" + setTypeString + ";nt=" + oldDataDto.getNt());
        if (chatType != oldDataDto.getNt() + 1) {
            if (!((modelTypeString.equals("LTE") || modelTypeString.equals("5G")) && modelTypeString.equals(setTypeString))) {
                dataString += "===> 模块类型不正确;设备模块：" + modelTypeString + "，配置模块类型：" + setTypeString + ";测试失败";
                throw new Exception(dataString);
            }
        }
        String callStatus = map.getString("callStatus");
        if ("1".equals(callStatus) && oldDataDto.getBs() != 0) {
            throw new Exception(dataString += "===>通讯模块拨号状态：拨号失败！");
        }
        json.put("chatModelType", oldDataDto.getSt() == 0 ? 1 : 0);
        String modelstatusString = oldDataDto.getSt() == 0 ? "模块正常" : "模块不正常";
        dataString += "===>模块状态：" + modelstatusString + ";";
        json.put("chatModelStatus", oldDataDto.getNt() + 1);
        dataString += "===>网络类型：" + modelTypeString + ";";
        json.put("chatDialingStatus", oldDataDto.getBs() == 0 ? 1 : 0);  //等于2为拨号成功
        String statString = oldDataDto.getBs() == 0 ? "拨号成功" : "拨号失败";
        dataString += "===>拨号状态：" + statString + ";";
        json.put("chatImei", oldDataDto.getImei());
        dataString += "===>IMEI号：" + oldDataDto.getImei() + ";";
        json.put("chatIp", oldDataDto.getIp());
        dataString += "===>IP地址：" + oldDataDto.getIp() + ";";
        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());

    }

    private void dealOrder_02_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                                OldDataDto oldDataDto, JSONObject map, JSONObject json, Integer type) throws Exception {
        mesIpcService.getVersion2(loginDto, cookiesMap, oldDataDto);
        String isOldAdaptIpc = map.getString("isOldAdaptIpc");
        if (null != isOldAdaptIpc && "Y".equals(isOldAdaptIpc)) {
            mesIpcService.getIpcSoftVersion(loginDto, cookiesMap, oldDataDto);
        }
        if (FrameUtil.isCheckWatch(map)) {
            mesIpcService.getWatchVersion2(loginDto, cookiesMap, oldDataDto);
        }
        if (FrameUtil.isCheckAvVer(map)) {
            mesIpcService.getAvverInfo2(loginDto, cookiesMap, oldDataDto);
        }
        String finalDataString = null;
        if (type == 1) {
            finalDataString = FrameUtil.dealOrder_02_2(oldDataDto, map, json);
        } else if (type == 2) {
            finalDataString = FrameUtil.dealOrder_02_chuzu_2(oldDataDto, map, json);
        }
        result.setCode(200);
        result.setData(finalDataString);
        result.setExtend(json.toJSONString());
    }

    private void dealOrder_27_2(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap, String id) throws Exception {
        // TODO 2.0版本，未找到写入终端ID的设置页面
        result.setCode(500);
        result.setMsg("未对接");
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_0a(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              String inputData, JSONObject map, JSONObject json) throws Exception {
        inputData = "config";
//        String cookies = JsoupUtils.setCookies(cookiesMap);
        String importPath = map.getString("importPath");
        if (StringUtils.isEmpty(importPath)) {
            result.setCode(500);
            result.setMsg("参数导入路径为空");
        }
        importPath = importPath.replaceAll("/", Matcher.quoteReplacement(File.separator)).replaceAll("\\\\", Matcher.quoteReplacement(File.separator));
        String path = importPath + File.separator + inputData;
        // 将 Map 转换为 String 格式的 Cookies
        String cookies = cookiesMap.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("; "));
        HttpClientUtil.doPostCookies(result, loginDto.getUploadUrl(), cookies, path);
        if (result.getCode().equals(200)) {
            String url = loginDto.getVersionUrl() + "?opt=writeLog&logParam=%E5%AF%BC%E5%85%A5%E5%8F%82%E6%95%B0%20%E7%BD%91%E7%BB%9C%E7%99%BB%E5%BD%95";
            /*
            Connection verConnect = Jsoup.connect(url);
            JsoupUtils.setCookies(verConnect, cookiesMap);
            Document verDocument = verConnect.get();*/
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet httpGet = new HttpGet(new URI(url));

                // 设置 Cookies
                for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                    httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
                }

                try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode != 200) {
                        // 可以在这里记录错误状态码或进行其他处理
                    }
                    // 注意：这里没有使用响应体，因此不需要读取实体
                }
            }
        }

    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_01(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        String finalData = null;
        String timeZone = map.getString("timeArea");
        if (StringUtils.isBlank(timeZone)) {
            throw new Exception("时区校验出错，交互配置未配置时区");
        }
        Map<String, String> map1 = new HashMap<>();
        map1.put("REQ", "{\"MODULE\":\"CONFIGMODEL\",\"SESSION\":\"FROMIE\",\"OPERATION\":\"GET\",\"PARAMETER\":{\"MDVR\":{\"TIMEP\":{\"DATEM\":\"?\",\"TIMEM\":\"?\",\"TIMEZ\":\"?\"}}}}");
//        Connection.Response execute = Jsoup.connect(loginDto.getMacUrl()).data(map1).cookies(cookiesMap).method(Connection.Method.POST).execute();
//        String body = execute.body();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 获取时区
            HttpPost httpPost = new HttpPost(new URI(loginDto.getMacUrl()));
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map1), "UTF-8"));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                String timez = "";
                try {
                    JSONObject parse = (JSONObject) JSONObject.parse(body);
                    JSONObject parameter = parse.getJSONObject("PARAMETER");
                    JSONObject mdvr = parameter.getJSONObject("MDVR");
                    JSONObject timep = mdvr.getJSONObject("TIMEP");
                    timez = timep.getString("TIMEZ");
                } catch (Exception e) {
                    throw new Exception("获取时区出错：" + e.getMessage());
                }
                Integer time = 0;
                try {
                    time = Integer.valueOf(timez.substring(0, timez.length() - 1));
                } catch (Exception e) {
                    throw new Exception("获取时区转换失败：" + timez.substring(0, timez.length() - 1) + "，错误信息：" + e.getMessage());
                }
                time = time / 60;
                if (!timeZone.equals(time + "")) {
                    throw new Exception("时区校验出错，工单获取时区：" + timeZone + ",配置设备时区：" + time);
                }

                // 获取系统时间
                String url = loginDto.getVersionUrl() + "?opt=systime&cmd=get";
                HttpGet httpGet = new HttpGet(new URI(url));

                // 设置 Cookies
                for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                    httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
                }

                try (CloseableHttpResponse responseTime = httpClient.execute(httpGet)) {
                    HttpEntity entityTime = responseTime.getEntity();
                    String verData = EntityUtils.toString(entityTime, "UTF-8");
                    JSONObject parseTime = (JSONObject) JSONObject.parse(verData);
                    String date = parseTime.getString("date");
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime of = LocalDateTime.parse(date, df);
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(now, of);
                    long minutes = duration.toMinutes();
                    if (minutes > 3 || minutes < -3) {
                        throw new Exception("时间校验出错，本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                                "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes);
                    }
                    String timeString = "===>本地时间：" + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                            "，配置设备时间：" + of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + ";相差：" + minutes;

                    finalData = "===> 设备时区：" + time + "，工单配置时区：" + timeZone + ";" + timeString + ";测试成功";

                    json.put("timeArea", String.valueOf(time));
                    json.put("machineDate", of);
                    result.setCode(200);
                    result.setData(finalData);
                    result.setExtend(json.toJSONString());
                }
            }
        }
    }

    private void dealOrder_25(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              String inputData) {
        result.setCode(200);
        result.setData("SN：" + inputData + ",写入成功");
    }

    private void dealOrder_03(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              OldDataDto oldDataDto, JSONObject map, JSONObject json, String inputData) throws Exception {
        mesIpcService.getDevMac(loginDto, cookiesMap, oldDataDto);
        String mac = inputData.replaceAll(":", "").replaceAll("：", "").replaceAll("-", "").toUpperCase();
        String clearMac = oldDataDto.getMac().replaceAll(":", "").replaceAll("：", "").replaceAll("-", "").toUpperCase();
        String fillData = "===> 设备MAC地址：" + clearMac;
        if (clearMac.equals(mac)) {
            fillData += ";测试成功";
            json.put("macAddress", mac);
        } else {
            fillData += ";输入的mac地址：" + mac + ";测试失败";
            throw new RuntimeException(fillData);
        }
        result.setCode(200);
        result.setData(fillData);
        result.setExtend(json.toJSONString());
    }

    private void dealOrder_07(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getDevInfo(loginDto, cookiesMap, oldDataDto);
        String dataString = "";
        String value = map.getString("value");
        String[] split = value.split("#");
        String signal = oldDataDto.getSignal();
        if (split.length == 1) {
            Integer signalInt = 0;
            Integer signalInt1 = 0;
            try {
                signalInt = Integer.valueOf(signal);
                signalInt1 = Integer.valueOf(value);
            } catch (Exception e) {
                throw new Exception("WIFI模块信号强度转换异常:" + e.getMessage());
            }
            if (signalInt > signalInt1) {
                dataString += "===> 本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度：" + signalInt1 + ",对比结果：大于;";
                json.put("chatSignal", signalInt);
            } else {
                dataString += "===> 信号强度不正确;本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度：" + signalInt1 + ",对比结果：小于等于;";
                throw new Exception(dataString);
            }
        } else {
            String limitString = "";
            Integer signalInt = 0;
            Integer signalInt1 = 0;
            Integer signalInt2 = 0;
            try {
                signalInt = Integer.valueOf(signal);
                signalInt1 = Integer.valueOf(split[0]);
                signalInt2 = Integer.valueOf(split[1]);
            } catch (Exception e) {
                throw new Exception("WIFI模块信号强度转换异常:" + e.getMessage());
            }
            limitString = "(" + signalInt1 + "~" + signalInt2 + ")";
            if (signalInt > signalInt1 && signalInt < signalInt2) {

                dataString += "===> 本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度设置范围：" + limitString + ";";
                json.put("chatSignal", signalInt);
            } else {
                dataString += "===> 信号强度不正确;本机WIFI模块信号强度：" + signalInt + ",工单获取WIFI模块信号强度设置范围：" + limitString + ",对比结果：小于等于;测试失败！";
                throw new Exception(dataString);
            }
        }
        if (json.getInteger("chatSignal") == 0) {
            json.put("wifiLinkStatus", 0);
            dataString += "===>WIFI连接状态：未连接;";
        } else {
            json.put("wifiLinkStatus", 1);
            dataString += "===>WIFI连接状态：连接成功;";
        }
        json.put("wifiMac", oldDataDto.getWifiMac());
        dataString += "===>WIFI MAC地址：" + oldDataDto.getWifiMac() + ";";
        json.put("wifiIp", oldDataDto.getWifiIp());
        dataString += "===>IP地址：" + oldDataDto.getWifiIp() + ";";
        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());
    }

    private void dealOrder_08(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              OldDataDto oldDataDto, JSONObject map, JSONObject json) throws Exception {
        mesIpcService.getDevInfo(loginDto, cookiesMap, oldDataDto);
        String dataString = "";
        if (StringUtils.isNotBlank(map.getString("gpsSum"))) {//工单未维护的不比对，直接通过
            Integer gpsSum1 = CastUtil.parseInt(map.getString("gpsSum"), "工单获取GPS模块卫星颗数");
            Integer gpsSum = CastUtil.parseInt(oldDataDto.getGpsSum(), "本机GPS模块卫星颗数");
            if (gpsSum >= gpsSum1) {
                dataString += "===> 本机GPS模块卫星颗数：" + gpsSum + ",工单获取GPS模块卫星颗数：" + gpsSum1 + ",对比结果：大于等于;";
                json.put("gpsSatellite", gpsSum);
            } else {
                dataString += "===> 本机GPS模块卫星颗数：" + gpsSum + ",工单获取GPS模块卫星颗数：" + gpsSum1 + ",对比结果：小于;";
                throw new Exception(dataString);
            }
        }
        json.put("gpsLinkStatus", oldDataDto.getGpsStatus() == 2 ? 1 : 0);//S
        String statuString = oldDataDto.getGpsStatus() == 2 ? "连接成功" : "未连接";
        dataString += "===>GPS连接状态：" + statuString + ";";
        json.put("gpsModelType", 0);  //未知,待定
        dataString += "===>GPS类型：GPS;";
        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());
    }

    private String compareOldData(OldDataDto oldDataDto, JSONObject sourceData, JSONObject json, String keySuffix, String oldKeySuffix) throws Exception {
        String dataString = "";
        if (null != oldDataDto) {
            //工单未维护时不需要比对，直接跳过
            if (StringUtils.isNotBlank(sourceData.getString("chatVersion" + keySuffix))) {
                String chatVersion = sourceData.getString("chatVersion" + keySuffix);
                String sver = oldDataDto.getSver();
                //模糊比对
                if (StringUtils.isNotBlank(sver) && sver.contains(chatVersion)) {
                    dataString += "===> 本机通讯模块" + oldKeySuffix + "版本号：" + sver + ",工单获取通讯模块" + keySuffix + "版本号：" + chatVersion + ",对比结果：相同;";
                    json.put("chatVersion" + keySuffix, sver);
                } else {
                    dataString += "===> 本机通讯模块" + oldKeySuffix + "版本号：" + sver + ",工单获取通讯模块" + keySuffix + "版本号：" + chatVersion + ",对比结果：不同;";
                    throw new Exception(dataString);
                }
            }
            //工单未维护时不需要比对，直接跳过
            if (StringUtils.isNotBlank(sourceData.getString("chatSignal" + keySuffix))) {
                String chatSignal = sourceData.getString("chatSignal" + keySuffix);
                String[] chatSignalSplit = chatSignal.split("#");
                String si = oldDataDto.getSi();
                String sr = oldDataDto.getSr();
                if (chatSignalSplit.length == 1) {
                    Integer siInt = 0;
                    Integer chatSignalInt = 0;
                    try {
                        siInt = Integer.valueOf(si);
                        chatSignalInt = Integer.valueOf(chatSignal);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new Exception("===> 信号强度转换失败,测试信号强度失败:" + e.getMessage());
                    }
                    if (siInt >= chatSignalInt) {
                        dataString += "===> 本机通讯模块" + oldKeySuffix + "信号强度：" + si + ",工单获取通讯模块" + keySuffix + "信号强度：" + chatSignal + ",对比结果：大于等于;";
                        json.put("chatSignal" + keySuffix, si);
                    } else {
                        dataString += "===> 本机通讯模块" + oldKeySuffix + "信号强度：" + si + ",工单获取通讯模块" + keySuffix + "信号强度：" + chatSignal + ",对比结果：小于;";
                        throw new Exception(dataString);
                    }
                } else {
                    String limitString = "";
                    Integer srInt = 0;
                    Integer chatSignalMinInt = 0;
                    Integer chatSignalMaxInt = 0;
                    try {
                        srInt = Integer.valueOf(sr);
                        chatSignalMinInt = Integer.valueOf(chatSignalSplit[0]);
                        chatSignalMaxInt = Integer.valueOf(chatSignalSplit[1]);
                    } catch (Exception e) {
                        throw new Exception("===> 信号强度转换失败,测试信号强度失败:" + e.getMessage());
                    }
                    limitString = "(" + chatSignalMinInt + "~" + chatSignalMaxInt + ")";
                    if (srInt >= chatSignalMinInt && srInt <= chatSignalMaxInt) {

                        dataString += "===> 本机通讯模块" + oldKeySuffix + "信号强度：" + srInt + ",工单获取通讯模块" + keySuffix + "信号强度设置范围：" + limitString + ";";
                        json.put("chatSignal" + keySuffix, srInt);
                    } else {
                        dataString += "===> 信号强度不正确;本机通讯模块" + oldKeySuffix + "信号强度：" + srInt + ",工单获取通讯模块" + keySuffix + "信号强度设置范围：" + limitString + ",对比结果：不在范围内;测试失败！";
                        throw new Exception(dataString);
                    }
                }
            }

            String modelTypeString = FrameUtil.getChatModelType(oldDataDto.getNt() + 1);
            if (StringUtils.isNotBlank(sourceData.getString("chatType" + keySuffix))) {
                Integer chatType = Integer.parseInt(sourceData.getString("chatType" + keySuffix));
                if (chatType != oldDataDto.getNt() + 1) {
                    String setTypeString = FrameUtil.getChatModelType(chatType);
                    if (!((modelTypeString.equals("LTE") || modelTypeString.equals("5G")) && modelTypeString.equals(setTypeString))) {
                        dataString += "===> 模块类型不正确;设备模块" + oldKeySuffix + "类型：" + modelTypeString + "，配置模块" + keySuffix + "类型：" + setTypeString + ";测试失败";
                        throw new Exception(dataString);
                    }
                }
            }

            if (StringUtils.isNotBlank(sourceData.getString("callStatus" + keySuffix))) {
                String callStatus = sourceData.getString("callStatus" + keySuffix);
                if ("1".equals(callStatus) && oldDataDto.getBs() != 2) {
                    throw new Exception(dataString += "===>通讯模块" + keySuffix + "【" + oldKeySuffix + "】拨号状态：拨号失败！");
                }
            }

            json.put("chatModelType" + keySuffix, oldDataDto.getBs() == 2 ? 1 : 0);
            String modelstatusString = oldDataDto.getBs() == 2 ? "模块正常" : "模块不正常";
            dataString += "===>模块" + keySuffix + "【" + oldKeySuffix + "】状态：" + modelstatusString + ";";

            json.put("chatModelStatus" + keySuffix, oldDataDto.getNt() + 1);
            dataString += "===>模块" + keySuffix + "【" + oldKeySuffix + "】网络类型：" + modelTypeString + ";";

            //等于2为拨号成功
            json.put("chatDialingStatus" + keySuffix, oldDataDto.getBs() == 2 ? 1 : 0);
            String statString = oldDataDto.getBs() == 2 ? "拨号成功" : "拨号失败";
            dataString += "===>模块" + keySuffix + "【" + oldKeySuffix + "】拨号状态：" + statString + ";";

            json.put("chatImei" + keySuffix, oldDataDto.getImei());
            dataString += "===>模块" + keySuffix + "【" + oldKeySuffix + "】IMEI号：" + oldDataDto.getImei() + ";";

            json.put("chatIp" + keySuffix, oldDataDto.getIp());
            dataString += "===>模块" + keySuffix + "【" + oldKeySuffix + "】IP地址：" + oldDataDto.getIp() + ";";
        } else {
            if (StringUtils.isNotBlank(sourceData.getString("chatVersion" + keySuffix))
                    || StringUtils.isNotBlank(sourceData.getString("chatSignal" + keySuffix))
                    || StringUtils.isNotBlank(sourceData.getString("chatType" + keySuffix))
                    || StringUtils.isNotBlank(sourceData.getString("callStatus" + keySuffix))) {
                dataString += "===> 本机通讯模块" + oldKeySuffix + "老化数据未获取到";
                throw new Exception(dataString);
            }
        }
        return dataString;
    }

    private void dealOrder_06(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap, JSONObject map) throws Exception {
        Map<String, OldDataDto> oldDataDtoMap = mesIpcService.getDevInfoList(loginDto, cookiesMap);
        JSONObject json = new JSONObject();

        String dataString = "";

        OldDataDto oldDataDto = oldDataDtoMap.get("G");
        dataString += compareOldData(oldDataDto, map, json, "", "G");

        oldDataDto = oldDataDtoMap.get("FG");
        dataString += compareOldData(oldDataDto, map, json, "2", "FG");

        oldDataDto = oldDataDtoMap.get("FIVEG");
        dataString += compareOldData(oldDataDto, map, json, "3", "FIVEG");

        result.setCode(200);
        result.setData(dataString + "测试成功");
        result.setExtend(json.toJSONString());
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_0e(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              JSONObject json) throws Exception {
        String fillData = "";
        String url = loginDto.getVersionUrl() + "?opt=sys&cmd=factoryid";
        /*
        Connection verConnect = Jsoup.connect(url);
        JsoupUtils.setCookies(verConnect, cookiesMap);
        Document verDocument = verConnect.get();
        String verData = verDocument.body().html();*/
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(new URI(url));

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                String verData = EntityUtils.toString(entity, "UTF-8");
                JSONObject parse = (JSONObject) JSONObject.parse(verData);
                String serial = parse.getString("serial");
                json.put("chipNumber", serial);
                fillData = "===>获取加密芯片号数据：" + serial + ";测试成功";
                result.setCode(200);
                result.setData(fillData);
                result.setExtend(json.toString());
            }
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_1c(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap,
                              String inputData) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("REQ", "{\"MODULE\":\"CONFIGMODEL\",\"OPERATION\":\"SET\",\"PARAMETER\":{\"MDVR\":{\"PS\":{\"PN\":\"" + inputData + "\"}}},\"SESSION\":\"FROMIE\"}");
        map.put("PAGEID", "base_set");
        //Connection.Response execute = Jsoup.connect(loginDto.getMacUrl()).data(map).cookies(cookiesMap).method(Connection.Method.POST).execute();
        //String body = execute.body();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(new URI(loginDto.getMacUrl()));
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), "UTF-8"));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                JSONObject parse = (JSONObject) JSONObject.parse(body);
                JSONObject data = parse.getJSONObject("RESPONSE");
                if (data.getInteger("ERRORCODE") != 0) {
                    throw new Exception("写入手机号失败");
                }


                String url = loginDto.getVersionUrl() + "?opt=writeLog&logParam=%E4%BF%9D%E5%AD%98%E9%85%8D%E7%BD%AE%20%E5%9F%BA%E6%9C%AC%E8%AE%BE%E7%BD%AE-%3E%E6%99%BA%E8%83%BD%E4%BA%A4%E9%80%9A-%3E%E5%9F%BA%E6%9C%AC%E8%AE%BE%E7%BD%AE%20%E7%BD%91%E7%BB%9C%E7%99%BB%E5%BD%95";
                HttpGet httpGet = new HttpGet(new URI(url));

                for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                    httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
                }

                try (CloseableHttpResponse responseLog = httpClient.execute(httpGet)) {
                    HttpEntity entityLog = responseLog.getEntity();
                    EntityUtils.consume(entityLog); // Consume the entity to close it properly
                }

                result.setCode(200);
                result.setData("写入手机号成功");
            }
        }
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    private void dealOrder_27(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap, String id) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("REQ", "{\"MODULE\":\"CONFIGMODEL\",\"OPERATION\":\"SET\",\"PARAMETER\":{\"MDVR\":{\"PSI\":{\"PI\":[{\"TID\":\"" + id + "\"},{\"TID\":\"" + id + "\"},{\"TID\":\"" + id + "\"},{\"TID\":\"" + id + "\"},{\"TID\":\"" + id + "\"},{\"TID\":\"" + id + "\"}]}}},\"SESSION\":\"FROMIE\"}");
        map.put("PAGEID", "base_set");
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 写入终端 ID 的 POST 请求
            HttpPost httpPost = new HttpPost(new URI(loginDto.getMacUrl()));
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), "UTF-8"));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            // 设置 Cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                JSONObject parse = (JSONObject) JSONObject.parse(body);
                JSONObject data = parse.getJSONObject("RESPONSE");
                if (data.getInteger("ERRORCODE") != 0) {
                    throw new Exception("写入终端ID失败");
                }

                String url = loginDto.getVersionUrl()
                        + "?opt=writeLog&logParam=%E4%BF%9D%E5%AD%98%E9%85%8D%E7%BD%AE%20%E5%9F%BA%E6%9C%AC%E8%AE%BE%E7%BD%AE-%3E%E6%99%BA%E8%83%BD%E4%BA%A4%E9%80%9A-%3E%E5%9F%BA%E6%9C%AC%E8%AE%BE%E7%BD%AE%20%E7%BD%91%E7%BB%9C%E7%99%BB%E5%BD%95";
                HttpGet httpGet = new HttpGet(new URI(url));

                // 设置 Cookies
                for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                    httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
                }

                try (CloseableHttpResponse responseLog = httpClient.execute(httpGet)) {
                    HttpEntity entityLog = responseLog.getEntity();
                    // 消费实体内容，确保所有数据被读取并且释放资源
                    EntityUtils.consume(entityLog);
                }

                result.setCode(200);
                result.setData("写入终端ID成功");
            }
        }
    }

    private void dealOrder_02(Result<String> result, LoginDto loginDto, Map<String, String> cookiesMap, OldDataDto oldDataDto, JSONObject map,
                              JSONObject json, Integer type) throws Exception {
        mesIpcService.getVersion(loginDto, cookiesMap, oldDataDto);
        if (FrameUtil.isCheckWatch(map)) {
            mesIpcService.getAibox(loginDto, cookiesMap, oldDataDto);
        }
        if (FrameUtil.isCheckAvVer(map)) {
            mesIpcService.getAvverInfo(loginDto, cookiesMap, oldDataDto);
        }
        String finalDataString = null;
        if (type == 1) {
            finalDataString = FrameUtil.dealOrder_02(oldDataDto, map, json);
        } else if (type == 2) {
            finalDataString = FrameUtil.dealOrder_02_chuzu(oldDataDto, map, json);
        }
        result.setCode(200);
        result.setData(finalDataString);
        result.setExtend(json.toJSONString());
    }


}
